package com.cn.ccp.util;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;

import org.apache.log4j.Logger;

import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;

public class Converter {
//	private static String pdf2swfPath = "C:/Program Files/SWFTools/pdf2swf.exe " ;
	private static Logger log = Logger.getLogger(Converter.class);
	public static int convertPDF2SWF(String sourcePath, String destPath, String fileName) throws IOException {
	   //目标路径不存在则建立目标路径
	   File dest = new File(destPath);
	   if (!dest.exists()) dest.mkdirs();
	  
	   //源文件不存在则返回
	   File source = new File(sourcePath);
	   if (!source.exists()) return 0;
	  
	   //调用pdf2swf命令进行转换
	   String command = CCPContants.pdf2SwfPath + " -o \"" + destPath + "\\" + fileName + "\"  -s flashversion=9 \"" + sourcePath + "\"";
	  
	   log.info(command);
	   Process pro = Runtime.getRuntime().exec(new String[]{CCPContants.pdf2SwfPath ,"-o",destPath + File.separator + fileName,"-s","flashversion=9",sourcePath});
	  
	   BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(pro.getInputStream()));
	   while (bufferedReader.readLine() != null); 
	  
	   try {
	    pro.waitFor();
	   } catch (InterruptedException e) {
	    // TODO Auto-generated catch block
	    e.printStackTrace();
	   }
	  
	   return pro.exitValue();
	  
	}
	
	public static void decodeFile(File srcFile){
		
	}
	
	
	
	public static synchronized void encodeFile(File srcFile){
		try{
			log.info(srcFile.getCanonicalPath());
			String fileName = srcFile.getName();
			String dest = srcFile.getParentFile().getAbsolutePath() + File.separator + "tmp.pdf";
			boolean f = srcFile.renameTo(new File(dest));
			FileInputStream in = new FileInputStream(dest);
	        File file = new File(srcFile.getParentFile().getAbsolutePath() + File.separator + fileName);
	        if(!file.exists())
	            file.createNewFile();
	        JNIUtil jni = new JNIUtil();
	        FileOutputStream out=new FileOutputStream(file);
	        byte buffer[]= jni.readFully(in);
	        int len = buffer.length;
	        byte[] tmp = new byte[1024];
	        int tmpLength = 0;
	        for(int i=0; i*1024<len;i++){
	        	tmpLength = len - i*1024;
	        	if(tmpLength >= 1024)
	        		System.arraycopy(buffer, i*1024, tmp, 0, 1024);
	        	else
	        		System.arraycopy(buffer, i*1024, tmp, 0, tmpLength);
	        	out.write(jni.encode(tmp));
	        }
	        in.close();
	        out.close();
	        new File(dest).delete();
		}catch(Exception e){
			log.error("encod file failed : ", e);
		}
	}
	
	public static File  convertTo(File file, String type){ 
	     File nowFile = file; 
	     String fileName = nowFile.getName(); 
	     int i = fileName.indexOf("."); 
	     int leg = fileName.length(); 
	     //获得传入文件的后缀名
	     String exName = (i > 0 ? (i + 1) == leg ? "" : fileName.substring(i, fileName.length()) : ""); 
	     //建立一个临时文件,用来保存目标文件;文件的名称和传进来的一样,类型为传入的类型
	     File toFile= new File(nowFile.getPath().replace(exName, "." + type)); 
	     OpenOfficeConnection connection  = null;
	     try { 
	         //连接openoffice 8100 端口和上面在DOS中启动服务设置的端口一致,这里还可以将openoffice放在别的机器上,通过IP和端口来连接,如果不填IP,则默认是localhost:
	//new SocketOpenOfficeConnection("192.168.0.120", 8100);
	    	 connection = new SocketOpenOfficeConnection( 8100);                      
	         connection.connect(); 
	         DocumentConverter converter = new OpenOfficeDocumentConverter( connection); 
	 //转换,传入源文件和目标文件;
	         converter.convert(nowFile, toFile); 
	//当openoffice服务是在远程机器上的时候要注意的是:nowFile必须在本地和远程都存在;不然会报错,原因未知;但转换后的内容则是按远程机器上的内容来的;被转换后的文件保存在远程服务器上;
	     } catch (ConnectException e) { 
	         e.printStackTrace();
	     }finally{
	    	 try{
		    	 if(connection != null){
		    		 connection.disconnect();
		    		 connection = null;
		    	 }
	    	 }catch(Exception e){}
	     } 
	     //返回目标文件
	     return toFile; 
	 }
	public static void main(String[] args) {
		File sourceFile = new File("F:\\workspace\\CCP\\tmp\\ddddd.doc");
		log.info("---------"+sourceFile.exists());
		log.info("----------"+System.getProperty("user.dir"));
		File pdfFile = new File("f:/ddddd.pdf");
		File swfFile = new File("f:/ddddd.swf");
		pdfFile = Converter.convertTo(sourceFile,"pdf");
		try {
			Converter.convertPDF2SWF(pdfFile.getPath(), swfFile.getParent(), swfFile.getName());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
